//
//  CZEmotionCell.swift
//  表情键盘
//
//  Created by Albert Zhu on 16/10/27.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

protocol CZEmotionCellDelegate: NSObjectProtocol {
    /// 在表情cell中选中了某个表情
    ///
    /// - parameter emotion: 表情类型/nil表示删除
    func emotionCell(_ emotionCell: CZEmotionCell, didSelectedEmotion emotion: CZEmotionModel?)
}

/// 表情页面cell，每个页面显示20个表情，和collectionView一样大小
class CZEmotionCell: UICollectionViewCell {
    
    @IBOutlet weak var label: UILabel!
    
    /// 表情选择提示视图
    private lazy var tipView = CZEmotionTipView()
    
    weak var delegate: CZEmotionCellDelegate?
    
    var emotions: [CZEmotionModel]? {
        didSet{
            for btn in contentView.subviews {
                btn.isHidden = true
            }
            
            contentView.subviews.last?.isHidden = false
            
            for (i, em) in (emotions ?? []).enumerated() {
                guard let btn = contentView.subviews[i] as? UIButton else {continue}
                
                btn.setImage(em.image, for: [])
                
                // 设置emoji字符串
                btn.setTitle(em.emoji, for: [])
                
                btn.isHidden = false
                let center = btn.center
                btn.sizeToFit()
                btn.center = center
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 界面在界面出现或从界面移除都会调用该方法
    ///
    /// - parameter newWindow:
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        
        guard let w = newWindow else {return}
        
        tipView.isHidden = true
        w.addSubview(tipView)
    }
    
    @objc func clickEmotionButton(sender: UIButton) {
        guard let emotions = emotions else {return}
        let tag = sender.tag
        
        var em: CZEmotionModel?
        
        if tag < emotions.count {
            em = emotions[tag]
        }
        
        delegate?.emotionCell(self, didSelectedEmotion: em)
        
        debugPrint(em)
    }
    
    /// 长按手势识别
    ///
    /// - parameter gesture: 手势
    @objc func longPress(gesture: UILongPressGestureRecognizer) {
        
        let location = gesture.location(in: self)
        
        guard let btn = buttonWithLocation(location: location) else {return}
        
        switch gesture.state {
        case .began, .changed:
            tipView.isHidden = false
            let center = self.convert(btn.center, to: window)
            tipView.center = center
            
            if btn.tag < (emotions?.count)! {
              tipView.emotion = emotions?[btn.tag]
            }
        case .ended:
            tipView.isHidden = true
            clickEmotionButton(sender: btn)
        case .cancelled, .failed:
            tipView.isHidden = true
        default:
            break
        }
    }
    
    private func buttonWithLocation(location: CGPoint) -> UIButton? {
        
        for btn in contentView.subviews as! [UIButton] {
            if btn.isHidden == false && btn.frame.contains(location) && btn != contentView.subviews.last {
                return btn
            }
        }
        
        return nil
    }
}

private extension CZEmotionCell {
    func setupUI() {
        
        /// 三行七列
        let rowCount = 3
        let colCount = 7
        
        /// 距离左右和下边的距离
        let leftMargin: CGFloat = 8
        let bottomMargin: CGFloat = 16
        
        for i in 0..<21 {
            let row = i % colCount
            let col = i / colCount
            
            let btnW = (bounds.width - leftMargin * 2) / CGFloat(colCount)
            let btnH = (bounds.height - bottomMargin) / CGFloat(rowCount)
            
            let rect = CGRect(x: leftMargin, y: 0, width: btnW, height: btnH)
            
            let btn = UIButton()
            btn.frame = rect.offsetBy(dx: CGFloat(row) * btnW, dy: CGFloat(col) * btnH)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            btn.tag = i
            btn.addTarget(self, action: #selector(clickEmotionButton), for: .touchUpInside)
            let longGes = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
            longGes.minimumPressDuration = 0.3
            if i != 20 {
                btn.addGestureRecognizer(longGes)
            }
            contentView.addSubview(btn)
        }
        
        /// 最后一个按钮是删除键，单独处理
        let btn = contentView.subviews.last as! UIButton
        
        let image = UIImage(named: "compose_emotion_delete", in: CZEmotionManager.shared.bundle, compatibleWith: nil)
        btn.setImage(image, for: [])
        let center = btn.center
        btn.sizeToFit()
        btn.center = center
    }
}
